package com.orange.adminapi.controller.user;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.orange.core.pojo.BR;
import com.orange.core.pojo.PageReqDto;
import com.orange.core.pojo.R;
import com.orange.core.pojo.entity.user.User;
import com.orange.core.pojo.enums.EStatus;
import com.orange.core.pojo.req.employee.EmployeeCardSaveReq;
import com.orange.core.pojo.req.user.UserSearchReq;
import com.orange.core.service.employee.EmployeeCardService;
import com.orange.core.service.user.UserService;
import com.orange.core.validator.group.Update;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 用户
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    private final EmployeeCardService employeeCardService;

    /**
     * 分页查询
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).USER_LIST.permission.identifier)")
    @PostMapping("/page")
    public R<Page<User>> page(@RequestBody PageReqDto<UserSearchReq> req) {
        return R.ok(userService.page(req));
    }

    /**
     * 编辑
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).USER_UPDATE.permission.identifier)")
    @PutMapping
    public R<Boolean> update(@RequestBody @Validated(Update.class) User user) {
        return R.ok(userService.update(user));
    }

    /**
     * 启用/禁用
     *
     * @param status 状态：0禁用，1启用
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).USER_STATUS.permission.identifier)")
    @PostMapping("/{id}/status/{status}")
    public R<Boolean> setStatus(@PathVariable int id, @PathVariable(value = "status", required = false) EStatus status) {
        return BR.result(userService.setStatus(id, status));
    }

    /**
     * 是否商管切换
     *
     * @param id       用户id
     * @param userType 用户类型：2 员工，3 商管
     */
    @PostMapping("/switch/{id}/{userType}")
    public R<Boolean> switchMerchant(@PathVariable int id, @PathVariable int userType) {
        return R.ok(userService.switchMerchantAdmin(id, userType));
    }

    /**
     * 换卡
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).USER_CHANGE.permission.identifier)")
    @PostMapping("/change")
    public R<Boolean> change(@RequestBody @Validated EmployeeCardSaveReq req) {
        return R.ok(employeeCardService.change(req));
    }

    /**
     * 解绑
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).USER_UNBIND.permission.identifier)")
    @PostMapping("/unbind/{userId}")
    public R<Boolean> status(@PathVariable int userId) {
        return R.ok(employeeCardService.unbind(userId));
    }
}
